//
//  TableView.m
//  MoneyIndividual
//
//  Created by Le Anh Tai on 1/9/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "TableView.h"
#import "TitleCell.h"

@implementation TableView

#pragma mark - Lifecycle
- (id)init
{
    self = [super init];
    
    if (self)
    {
        [self initializeTableView];
    }
    
    return self;
}

#pragma mark - Logic functions
- (void)setFrame:(CGRect)frame
{
    frame = RECT(0, frame.origin.y, SCREEN_SIZE.width, HEI_CELL_DEFAULT*4);
    [super setFrame:frame];
    
    _tableView.frame = self.bounds;
}

- (void)initializeTableView
{
    _tableView = [[UITableView alloc] init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self addSubview:_tableView];
}

- (void)setSelectedObject:(id)selectedObject
{
    _selectedObject = selectedObject;
    if (_selectedObject)
    {
        int selectedIndex = [_objects indexOfObject:_selectedObject];
        [_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:selectedIndex inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    }
    else
    {
        [_tableView selectRowAtIndexPath:nil animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

- (void)setObjects:(NSArray *)objects
{
    _objects = objects;
    
    [_tableView reloadData];
}

#pragma mark - Delegate UITableView

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return _objects.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEI_CELL_DEFAULT;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString *cellIdentifier = @"TitleCell";
    
    TitleCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil)
    {
        cell = [[TitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    id object = [_objects objectAtIndex:indexPath.row];
    
    if ([object isKindOfClass:[NSManagedObject class]])
    {
        cell.titleLabel.text = [object valueForKeyEx:NAME_KEY];
    }
    else if([object isKindOfClass:[NSString class]])
    {
        cell.titleLabel.text = object;
    }    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _selectedObject = [_objects objectAtIndex:indexPath.row];
    if ([_delegate respondsToSelector:@selector(table:didSelectManageObject:)])
    {
        [_delegate table:self didSelectManageObject:_selectedObject];
    }
}

@end